package com.sunnypower.rushfitapp.Coursepart;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.sunnypower.rushfitapp.R;
import com.sunnypower.rushfitapp.entity.Coach;

import java.util.List;


public class CoachListAdapter extends BaseAdapter {

    private List<Coach> mList;
    private Context mContext;
    private LayoutInflater mLayoutInflater;


    public CoachListAdapter(Context context, List<Coach> list) {
        mContext = context;
        mList = list;
        mLayoutInflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return mList.size();
    }

    @Override
    public Object getItem(int position) {
        return mList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        if (convertView == null) {
            viewHolder = new ViewHolder();
            convertView = mLayoutInflater.inflate(R.layout.coach_list_item, null);
            viewHolder.img_coach = convertView.findViewById(R.id.img_coach);
            viewHolder.tv_coachname = convertView.findViewById(R.id.tv_coachname);
            viewHolder.tv_coachname.setSelected(true);
            viewHolder.tv_slogan = convertView.findViewById(R.id.tv_slogan);
            viewHolder.tv_slogan.setSelected(true);
            viewHolder.reward = convertView.findViewById(R.id.reward);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        Coach bean = mList.get(position);
        String photo = bean.getPhoto();
        Bitmap decodedByte = null;
        if (photo == "" || photo == null) {
            decodedByte = null;
        }else {
            byte[] decodedString = Base64.decode(bean.getPhoto().split(",")[1], Base64.DEFAULT);
             decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
        }
        String sex = "女";
        if (bean.getSex() == 1) {
            sex = "男";
        }
        viewHolder.img_coach.setImageBitmap(decodedByte);
        viewHolder.tv_coachname.setText(bean.getName() + " | " + sex);
        viewHolder.tv_slogan.setText(bean.getInfo());
        viewHolder.reward.setText(bean.getAward());
        return convertView;
    }

    private static class ViewHolder {
        public ImageView img_coach;
        public TextView tv_coachname;
        public TextView tv_slogan;
        public TextView reward;
    }
}
